const sqlExqute = require('../../database/acl/query')
//---加载crypto
const crypto = require('crypto')
// 生成token
const jwt = require('jsonwebtoken')
const { jwtSecretKey } = require('../../config')

// 用户登录
const handlerUserLogin = async (req, res) => {
  const userInfo = req.body
  const sql = 'select * from admin where username=?'
  const value = userInfo.username
  let result = await sqlExqute(sql,value)
  //---定义使用MD5加密
  const md5 = crypto.createHash('md5');
  //---输出加密的密码
  const md5crypo = md5.update(userInfo.password).digest('hex')

  if (result.length > 0) {
    // 排除密码
    const user = { ...result[0], password: ''}
    const token = 'Bearer ' + jwt.sign(user, jwtSecretKey, { expiresIn: '72h'})
    result[0].password === md5crypo ? res.send({code:20000,msg:'登陆成功',data:{token}}) : res.cc('密码错误,登录失败,密码是111111')
  } else {
    res.cc('用户不存在')
  }
}

// 获取用户信息
const handlerGetUserInfo = (req, res) => {
  // 去除bearer
  const token = req.query.token.split(' ')[1]
  let user = {}
   //解密token
  jwt.verify(token, jwtSecretKey, (error, authData) => {
    if (error) {
      res.send({code:40000,msg:'token过期'})
    } else {
      user = authData;
      res.send({code:20000,msg:'登陆成功',data:{...user}})
    }
  })

}

module.exports = {
  handlerUserLogin,
  handlerGetUserInfo,

}
